package cn.edu.swu.auth;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/user/userLogin")
public class UserLoginServlet extends HttpServlet {

    private UserLoginService loginService;

    @Override
    public void init() throws ServletException {
        super.init();
        UserRepo userRepo = new UserRepo(); // 假设UserRepo类已经实现了数据库操作
        this.loginService = new UserLoginService(userRepo);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("user");
        String password = request.getParameter("pass");
        String code = request.getParameter("code");

        try {
            if (loginService.authenticateUser(username, password, code, request, response)) {
                // 对应UserAuthenticationFilter
                HttpSession session = request.getSession(true);
                session.setAttribute(UserAuthenticationFilter.LOGIN_TAG, UserAuthenticationFilter.LOGIN_SUCCESS);

                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\": true, \"message\": \"登录成功\"}");
            } else {

                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                String message = (String) request.getAttribute("loginError");
                response.getWriter().write("{\"success\": false, \"message\": \"" + message + "\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();

            response.sendRedirect("./sign-in.html");
        }
    }
}
